package com.example.controller;

import com.example.repository.ChatHistoryRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.aop.support.AbstractPointcutAdvisor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import static org.springframework.ai.chat.memory.ChatMemory.CONVERSATION_ID;

@RequiredArgsConstructor
@RestController
@RequestMapping("/ai")
public class ChatController {

    private final ChatClient chatClient;
    private final ChatHistoryRepository chatHistoryRepository;

    @RequestMapping("/chat1")
//    阻塞式返回（全部输出完才返回）
    public String chat(String prompt) {
        return chatClient.prompt()
                .user(prompt)
                .call()
                .content();
    }

//    流式返回（输出过程中返回）
    //这里要在返回值加上 produces = "text/html;charset=utf-8"，否则会乱码
    @RequestMapping(value = "/chat", produces = "text/html;charset=utf-8")
    //再传入一个chatId
    public Flux<String> stream(String prompt, String chatId) {
        //保存会话记录
        chatHistoryRepository.save("chat", chatId);

        return chatClient.prompt()
                .user(prompt)
                //这里的key值是一个固定的参数，不能随便修改
                .advisors(a -> a.param(CONVERSATION_ID, chatId) )
                .stream()
                .content();
    }
}
